<template>
  <div>
    <!-- 面包屑导航 -->
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>
      <!-- 步骤条区域 -->
      <el-steps :space="200" :active="activeIndex - 0" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 标签页 -->
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="ruleFormref"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <el-tabs
          :tab-position="tabPosition"
          v-model="activeIndex"
          :before-leave="beforTabLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>

            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>

            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>

            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>

            <el-form-item label="商品分类">
              <el-cascader
                v-model="addForm.goods_cat"
                :props="cateProps"
                :options="dataList"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :headers="headersURL"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="addbtn" @click="add">添加商品</el-button>
          </el-tab-pane>
          <!-- 添加商品 -->
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 对话框 -->
    <el-dialog title="图片预览" :visible.sync="dialogVisiblePic" width="50%">
      <img :src="pictureUrl" alt="" class="img1" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'Add',
  data() {
    return {
      activeIndex: '0',
      tabPosition: 'left',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs:[]
      },
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true,
      },
      manyTableData: [],
      addRules: {
        goods_name: [
          {
            required: true,
            message: '请输入商品的名称',
            trigger: 'blur',
          },
        ],
        goods_price: [
          {
            required: true,
            message: '请输入商品的价格',
            trigger: 'blur',
          },
        ],
        goods_weight: [
          {
            required: true,
            message: '请输入商品的重量',
            trigger: 'blur',
          },
        ],
        goods_number: [
          {
            required: true,
            message: '请输入商品的数量',
            trigger: 'blur',
          },
        ],
        // goods_list: [
        //   {
        //     required: true,
        //     message: '请选择商品的分类',
        //     trigger: 'blur',
        //   },
        // ],
      },
      dataList: [],
      onlyTableData: [],
      headersURL: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      pictureUrl: '',
      dialogVisiblePic: false,
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      const { data: res } = await this.$http.get(`categories`)
      if (res.meta.status !== 200) {
        this.$message.error('获取列表失败')
      } else {
        this.$message.success('获取列表成功')
        this.dataList = res.data
        console.log(this.dataList)
      }
    },
    handleChange(value) {
      // console.log(value)
      console.log(this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    beforTabLeave(activeName, oldName) {
      // console.log('即将进入的是'+activeName + '即将离开的是' + oldName);
      if (oldName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('切换页签失败')
        return false
      }
    },
    async tabClick() {
      // console.log(this.activeIndex);
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.addForm.goods_cat[2]}/attributes`,
          {
            params: {
              sel: 'many',
            },
          }
        )
        if (res.meta.status !== 200) {
          this.$message.error('请求失败')
        }
        // console.log(res.data)
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
        console.log(this.manyTableData)
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.addForm.goods_cat[2]}/attributes`,
          {
            params: {
              sel: 'only',
            },
          }
        )
        if (res.meta.status !== 200) {
          this.$message.error('请求失败')
        }
        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    handleRemove(file) {
      let path = file.response.data.tmp_path
      let i = this.addForm.pics.indexOf((x) => x.pic === path)
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm.pics)
    },
    handlePreview(file) {
      console.log(file)
      const priveUrl = file.response.data.url
      this.pictureUrl = priveUrl
      this.dialogVisiblePic = true
    },
    handleSuccess(response) {
      // console.log(response.data.tmp_path);
      const picInfo = {
        pic: response.data.tmp_path,
      }
      this.addForm.pics.push(picInfo)
      console.log(this.addForm.pics)
    },
    add(){
      console.log(this.addForm);
      this.$refs.ruleFormref.validate(async valid => {
        if (!valid){
          return this.$message.error('必填项没有填')
        }
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        this.manyTableData.forEach(item => {
          const newObj = {attr_id:item.attr_id,attr_value:item.attr_vals.join(' ')}
          this.addForm.attrs.push(newObj)
        })

        this.onlyTableData.forEach(item => {
          const newObj = {attr_id:item.attr_id,attr_value:item.attr_vals}
          this.addForm.attrs.push(newObj)
        })
        form.attrs = this.addForm.attrs

        const {data:res} = await this.$http.post('goods',form)
        if(res.meta.status !== 201){
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.$router.push('/goods')
        console.log(form);
      })
    }
  },
  watch: {
    // addForm: {
    //   handler(newname, oldname) {
    //     console.log(newname, oldname)
    //   },
    //   immediate: true,
    //   deep: true,
    // },
  },
}
</script>

<style scoped>
.el-steps {
  margin: 20px 0;
}
.el-dialog {
  overflow: hidden;
}
.img1 {
  width: 100%;
}
.addbtn{
  margin-top: 20px;
}
</style>
